package com.geniusk.system.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.geniusk.common.core.JSONResult;
import com.geniusk.common.utils.PageUtil;
import com.geniusk.system.model.bo.user.*;
import com.geniusk.system.model.pojo.Role;
import com.geniusk.system.model.pojo.User;
import com.geniusk.system.model.vo.UserVO;
import com.geniusk.security.annotation.PreFuncAuth;
import com.geniusk.security.utils.SecurityUtil;
import com.geniusk.system.service.UserRoleService;
import com.geniusk.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户管理接口
 */
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * ID查询用户
     * @param selectUserByIdBO 用户ID
     * @return 用户信息
     */
    @PostMapping("/selectUserById")
    public JSONResult selectUserById(@Valid @RequestBody SelectUserByIdBO selectUserByIdBO) {
        User user = userService.selectUserById(selectUserByIdBO.getUserId());
        UserVO userVO = JSONUtil.parse(user).toBean(UserVO.class);
        List<Role> roleList = user.getRoles();
        List<String> roleIds = new ArrayList<>();
        for(Role role:roleList){
            roleIds.add(role.getRoleId().toString());
        }
        userVO.setRoleIds(roleIds);
        Map<String,Object> result = new HashMap<>();
        result.put("user",userVO);
        return JSONResult.ok(result);
    }

    /**
     * 分页查询用户
     * @param selectUserByPageBO 用户
     * @return 用户列表
     */
    @PostMapping("/selectUserByPage")
    @PreFuncAuth("SYS:USER:SELECT")
    public JSONResult selectUserByPage(@Valid @RequestBody SelectUserByPageBO selectUserByPageBO){
        int pageNum = selectUserByPageBO.getPageNum();
        int pageSize = selectUserByPageBO.getPageSize();
        User user = JSONUtil.parse(selectUserByPageBO).toBean(User.class);
        PageUtil.startPage(pageNum,pageSize);
        List<User> userList = userService.selectUserByPage(user);
        Map<String,Object> result = PageUtil.getResultTableData(userList);
        return JSONResult.ok(result);
    }

    /**
     * 添加用户
     * @param insertUserBO 用户信息
     * @return 添加结果
     */
    @PostMapping("/insertUser")
    @PreFuncAuth("SYS:USER:INSERT")
    public JSONResult insertUser(@Valid @RequestBody InsertUserBO insertUserBO) {
        //查询用户名是否存在
        boolean isExist = userService.selectUsernameIsExist(insertUserBO.getUsername());
        if(isExist){
            return JSONResult.errorMsg("用户名已经存在");
        }
        User user = JSONUtil.parse(insertUserBO).toBean(User.class);
        Long userId = IdUtil.getSnowflake().nextId();
        user.setUserId(userId);
        user.setCreateBy(SecurityUtil.getUsername());
        user.setPassword(SecurityUtil.encryptPassword(IdUtil.fastUUID()));
        int rows = userService.insertUser(user);
        userRoleService.insertUserAuth(userId, insertUserBO.getRoleIds());
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    /**
     * 修改用户
     * @param updateUserBO 用户信息
     * @return 修改结果
     */
    @PostMapping("/updateUser")
    @PreFuncAuth("SYS:USER:UPDATE")
    public JSONResult updateUser(@Valid @RequestBody UpdateUserBO updateUserBO) {
        User user = JSONUtil.parse(updateUserBO).toBean(User.class);
        user.setUpdateBy(SecurityUtil.getUsername());
        int rows = userService.updateUser(user);
        userRoleService.insertUserAuth(updateUserBO.getUserId(), updateUserBO.getRoleIds());
        Map<String,Object> result = new HashMap<>();
        result.put("rows",rows);
        return JSONResult.ok(result);
    }

    /**
     * 删除用户
     * @param deleteUserByIdsBO 用户ID
     * @return 删除结果
     */
    @PostMapping("/deleteUserByIds")
    @PreFuncAuth("SYS:USER:DELETE")
    public JSONResult deleteUserByIds(@Valid @RequestBody DeleteUserByIdsBO deleteUserByIdsBO) {
        Long userId = SecurityUtil.getUserId();
        if (ArrayUtil.contains(deleteUserByIdsBO.getUserIds(), userId)) {
            return JSONResult.errorMsg("您不能删除自己的帐户");
        }
        int rows = userService.deleteUserByIds(deleteUserByIdsBO.getUserIds());
        HashMap<String,Object> result = new HashMap<>();
        result.put("rows", rows);
        return JSONResult.ok(result);
    }

    /**
     * 用户授权角色
     * @param insertUserRoleBO 用户角色关系
     * @return 授权结果
     */
    @PostMapping("/insertAuthRole")
    @PreFuncAuth("SYS:USER:UPDATE")
    public JSONResult insertAuthRole(@Valid @RequestBody InsertUserRoleBO insertUserRoleBO)
    {
        int rows = userRoleService.insertUserAuth(insertUserRoleBO.getUserId(), insertUserRoleBO.getRoleIds());
        HashMap<String,Object> result = new HashMap<>();
        result.put("rows", rows);
        return JSONResult.ok(result);
    }
}
